package jee.boot.common.basic.result;

import com.google.common.collect.Maps;
import jee.boot.entity.system.Filter;
import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.remote.RemoteEndpoint;
import jee.boot.common.utils.HttpServletHolder;
import jee.boot.common.utils.MatcherCompilationHelper;
import jee.boot.common.utils.SpringEnvironmentHolder;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.system.MessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class MessageCodeHelper {
    @Autowired
    private ProjectConfig projectConfig;
    @Autowired
    private RemoteEndpoint remoteEndpoint;
    /**
     * 消息码缓存
     * <language,<code,MessageCode>>
     */
    private Map<String, Map<Integer, MessageCode>> messageCodeMap = Maps.newHashMap();

    /**
     * 获取消息内容
     *
     * @param code
     * @return
     */
    public String getMessage(Integer code) {
        return getMessage(code, null, null);
    }

    /**
     * 获取消息内容
     *
     * @param code           消息码
     * @param data           消息数据
     * @param defaultMessage 默认消息内容
     * @return 消息内容
     */
    public String getMessage(Integer code, Object data, String defaultMessage) {
        MessageCode messageByCode = getMessageByCode(code);
        if (messageByCode != null) {
            String label = defaultMessage;
            if (messageByCode.getI18n() != null) {
                label = messageByCode.getI18n().getLabel();
            }
            if (data != null) {
                return MatcherCompilationHelper.simpleCompilation(data, label);
            } else {
                return label;
            }
        }
        return defaultMessage;
    }

    public MessageCode getMessageByCode(Integer code) {
        String language = HttpServletHolder.getLanguage();
        if (!messageCodeMap.containsKey(language)) {
            messageCodeMap.put(language, Maps.newHashMap());
        }
        Map<Integer, MessageCode> integerMessageCodeMap = messageCodeMap.get(language);
        // 未加载,或者需要实时加载
        if (!integerMessageCodeMap.containsKey(code) || projectConfig.isRealTimeLoadingMessageCode()) {
            MessageCode messageCode = new MessageCode();
            messageCode.addFilter(new Filter("code", "=", code));
            List<MessageCode> list = getMessageList(messageCode);
            if (list != null && !list.isEmpty()) {
                integerMessageCodeMap.put(code, list.get(0));
            }
        }
        if (integerMessageCodeMap.containsKey(code)) {
            return integerMessageCodeMap.get(code);
        } else {
            return null;
        }


    }

    private List<MessageCode> getMessageList(MessageCode messageCode) {
        return remoteEndpoint.executePost(projectConfig.getOpenSystemServer(), "/messageCode/all", messageCode, MessageCode.class);
    }

}
